import re


def create_mysql_insert_trigger(dir_path, insert_args_str, insert_vals_str):
    tar_dir = dir_path.split("/")[-1]
    export_file_name = tar_dir + "_insert"
    op_db_type = tar_dir.split("4")[0]
    op_db_dbs = tar_dir.split("4")[1]
    kear_table_name = op_db_dbs.split("2")[0]
    tb_kear_table_name = op_db_dbs.split("2")[1]
    str = f"DELIMITER $$\n" \
          f"CREATE TRIGGER trigger_{kear_table_name}_insert AFTER INSERT\n" \
          f"ON kaer.{kear_table_name} FOR EACH ROW begin\n" \
          f"insert into tb_kaer.{tb_kear_table_name}({insert_args_str}) values  ({insert_vals_str});\n" \
          f"end $$\n" \
          "DELIMITER ;"
    output = open(dir_path + "/" + export_file_name, 'x')
    output.write(str)


def create_mysql_update_trigger(dir_path, update_str, update_condition):
    tar_dir = dir_path.split("/")[-1]
    export_file_name = tar_dir + "_update"
    op_db_type = tar_dir.split("4")[0]
    op_db_dbs = tar_dir.split("4")[1]
    kear_table_name = op_db_dbs.split("2")[0]
    tb_kear_table_name = op_db_dbs.split("2")[1]
    str = f"DELIMITER $$\n" \
          f"CREATE TRIGGER `trigger_{kear_table_name}_update` AFTER  UPDATE ON `{kear_table_name}` FOR EACH ROW BEGIN\n" \
          f"update tb_kaer.{tb_kear_table_name} set {update_str} WHERE {update_condition};\n" \
          f"end $$\n" \
          f"DELIMITER ;"
    output = open(dir_path + "/" + export_file_name, 'x')
    output.write(str)


def create_mysql_delete_trigger(dir_path, delete_condition):
    tar_dir = dir_path.split("/")[-1]
    export_file_name = tar_dir + "_delete"
    op_db_type = tar_dir.split("4")[0]
    op_db_dbs = tar_dir.split("4")[1]
    kear_table_name = op_db_dbs.split("2")[0]
    tb_kear_table_name = op_db_dbs.split("2")[1]
    str = f"DELIMITER $$\n" \
          f"CREATE TRIGGER `trigger_{kear_table_name}_delete` AFTER  DELETE ON `{kear_table_name}` FOR EACH ROW BEGIN\n" \
          f"DELETE FROM tb_kaer.{tb_kear_table_name} WHERE {delete_condition};\n" \
          f"end $$\n" \
          f"DELIMITER ;"
    output = open(dir_path + "/" + export_file_name, 'x')
    output.write(str)


def create_cols_mappings(dir_path):
    tar_dir = dir_path.split("/")[-1]
    cur_file_path = tar_dir.split("4")[1] + ".txt"
    cols_mappings_file = open(dir_path + "/" + cur_file_path)
    cols_mappings_str = cols_mappings_file.read()
    cols_mappings_str = cols_mappings_str.replace(" as ", "=") \
        .replace("\r", "") \
        .replace("\n", "") \
        .replace(" ", "") \
        .replace("\t", "").strip(",")

    # print(cols_mappings_str.find(r"(?<=\(),(?=\))"))
    concat_strs = re.findall(r"\(.*\)", cols_mappings_str)
    cols_mappings_str_temp = cols_mappings_str
    for concat_str in concat_strs:
        # print(concat_str)
        concat_str_temp = str(concat_str).replace(",", "|")
        # print(concat_str_temp)
        cols_mappings_str_temp = cols_mappings_str_temp.replace(concat_str, concat_str_temp)
    print(cols_mappings_str)
    print(cols_mappings_str_temp)

    elems = cols_mappings_str_temp.split(",")
    args = []
    vals = []
    tab_id = "id"
    tab_id_val = ""

    for elem in elems:
        if ("=" in elem):
            elem_components = elem.split("=")
            if (elem_components[1] == "id"):
                tab_id_val = elem_components[0]
            args.append(elem_components[1])
            vals.append(elem_components[0])
        else:
            args.append(elem)
            vals.append(elem)

    # 生成insert所需字段组合
    # 生成update所需映射组合
    insert_args_str = ""
    insert_vals_str = ""
    update_str = ""
    for i in range(0, len(args)):
        insert_args_str += str(args[i]) + ","
        insert_vals_str += "NEW." + str(vals[i]) + ","
        if (args[i].upper() != "ID"):
            update_str += str(args[i]) + "=" + "NEW." + vals[i] + ","

    update_condition = tab_id + "=NEW." + tab_id_val
    update_condition = update_condition.replace("|", ",")
    delete_condition = tab_id + "=OLD." + tab_id_val
    delete_condition = delete_condition.replace("|", ",")
    insert_args_str = insert_args_str.strip(",")
    insert_vals_str = insert_vals_str.strip(",").replace("|", ",")
    update_str = update_str.strip(",").replace("|", ",")
    create_mysql_insert_trigger(dir_path, insert_args_str, insert_vals_str)
    create_mysql_update_trigger(dir_path, update_str, update_condition)
    create_mysql_delete_trigger(dir_path, delete_condition)
